// pages/conference/input_first.js
import { this_year, next_year, my_request, my_showToast_error, my_showToast_ok, gen_query_str } from '../../utils/my_utils'

Page({
    /**
     * 页面的初始数据
     */
    data: {
        identities: wx.getStorageSync('publisher-identities'),
        identities_id: wx.getStorageSync("publisher-identities-ids"),
        index: 0,
        start_date: this_year(),
        end_date: next_year(),
        region_seted: false,
        region: [, ,],//['广东省', '广州市', '海珠区'],
        customItem: '全部',
        next_url: '/pages/conference/input_second',
        loading: false,
        submit_data: {
            identity_id: wx.getStorageSync('publisher-identities')[0]
        },
        submit_data_length: {},
        maxlength: {
            conference_name: 25,
            conference_intro: 50,
            conference_location: 50
        },
        must_fields: [
            {
                key: 'conference_name',
                value: "会议名称",
            },
            {
                key: "conference_intro",
                value: "会议简介"
            },
            {
                key: 'region',
                value: "地区"
            },
            {
                key: "conference_location",
                value: "会议地址"
            },
            {
                key: "date",
                value: "会议日期"
            },
            {
                key: 'time',
                value: "会议时间"
            }
        ],
        init_warning_danger: {
            conference_name: "",
            conference_intro: "",
            conference_location: "",
            date: "",
            time: "",
            region: ""
        },
        init_submit_data: {}
    },
    valid_submit_data: function () {
        var submit_data = this.data.submit_data;
        var must_fields = this.data.must_fields
        var key = "";
        var desc = "";
        for (var i = 0; i < must_fields.length; ++i) {
            key = must_fields[i].key;
            desc = must_fields[i].value;
            if (!submit_data[key]) {
                var warning_danger = { ...this.data.init_warning_danger }
                //console.log(warning_danger)
                warning_danger[key] = "danger"
                this.setData({
                    warning_danger: warning_danger
                })
                my_showToast_error("输入错误", 2000)
                return false;
            }
        }
        return true;
    },
    identity_change: function (e) {
        this.setData({
            index: e.detail.value
        })
    },
    bindTimeChange: function (e) {
        var submit_data = this.data.submit_data;
        submit_data.time = e.detail.value;
        this.setData({
            submit_data: submit_data
        })
    },
    bindDateChange: function (e) {
        var submit_data = this.data.submit_data;
        submit_data.date = e.detail.value;
        this.setData({
            submit_data: submit_data
        })
    },
    bindRegionChange: function (e) {
        var submit_data = this.data.submit_data;
        submit_data.region = e.detail.value.join(";");
        //submit_data.
        //console.log(submit_data.region);
        this.setData({
            region: e.detail.value,
            region_seted: true,
            submit_data: submit_data
        })
    },

    input_text: function (e) {
        var var_name = e.currentTarget.dataset.name;
        var max_length = +e.currentTarget.dataset.maxlength;
        var value = e.detail.value;
        var cursor = e.detail.cursor;
        var submit_data = this.data.submit_data;
        var submit_data_length = this.data.submit_data_length;
        submit_data[var_name] = value;
        submit_data_length[var_name] = value.length;
        this.setData({
            submit_data: submit_data,
            submit_data_length: submit_data_length
        })
    },
    /**
     * 生命周期函数--监听页面加载
     */
    load_edit_cache: function () {
        //console.log(wx.getStorageSync("first-step-cache"));
        var region = wx.getStorageSync("first-step-cache").submit_data.region.split(';')
        this.setData({
            index: wx.getStorageSync("first-step-cache").index,
            submit_data: { ...wx.getStorageSync("first-step-cache").submit_data },
            init_submit_data: { ...wx.getStorageSync("first-step-cache").submit_data },
            region: region,
            region_seted: true
        })
        //console.log(this.data.region)
    },
    onLoad: function (options) {
        this.save_props(options)
        this.setData({
            warning_danger: { ...this.data.init_warning_danger }
        });
        //console.log(options)
        var edit_id = options.edit_id;
        if (edit_id) {
            this.load_conference(edit_id);
        }
        else if (options.back === "cache") {
            this.load_edit_cache()
        }
    },

    load_conference: function (id) {
        var that = this;
        this.setData({
            loading: true
        })
        //寻找缓存
        var conference_data = wx.getStorageSync("current-edit-conference");
        if (conference_data) {
            if (this.data.query_data.edit_id == conference_data.id) {
                var transformed_data = that.transform_meeting_data(conference_data);
                var submit_data = {};
                submit_data.conference_name = transformed_data.conference_name;
                submit_data.conference_intro = transformed_data.conference_intro;
                submit_data.date = transformed_data.date;
                submit_data.time = transformed_data.time;
                if (transformed_data.region) {
                    submit_data.region = transformed_data.region
                    that.setData({
                        region: submit_data.region.split(';'),
                        region_seted: true
                    })
                }
                submit_data.conference_location = transformed_data.conference_location
                if (transformed_data.creat_identity_id) {
                    var loaded_identities = that.data.identities;
                    for (var i = 0; i < loaded_identities.length; ++i) {
                        var creat_identity_id = +transformed_data.creat_identity_id;
                        if (loaded_identities[i] == creat_identity_id) {
                            that.setData({
                                index: i
                            })
                        }
                    }
                }
                that.setData({
                    submit_data: submit_data,
                    init_submit_data: { ...submit_data },
                    loading: false
                })
                return
            }
        }
        //没找到
        my_request({
            url: 'https://sichuangyi.demopp.in/api-conference-alpha/conference-detail',
            method: "GET",
            data: {
                meeting_id: id
            },
            success: function (res) {

                var conference_data = res.data.data.conference;
                wx.setStorageSync("current-edit-conference", conference_data);
                var transformed_data = that.transform_meeting_data(conference_data);
                var submit_data = {};
                submit_data.conference_name = transformed_data.conference_name;
                submit_data.conference_intro = transformed_data.conference_intro;
                submit_data.date = transformed_data.date;
                submit_data.time = transformed_data.time;
                if (transformed_data.region) {
                    submit_data.region = transformed_data.region
                    that.setData({
                        region: submit_data.region.split(';'),
                        region_seted: true
                    })
                }
                submit_data.conference_location = transformed_data.conference_location
                if (transformed_data.creat_identity_id) {
                    var loaded_identities = that.data.identities;
                    for (var i = 0; i < loaded_identities.length; ++i) {
                        var creat_identity_id = +transformed_data.creat_identity_id;
                        if (loaded_identities[i] == creat_identity_id) {
                            that.setData({
                                index: i
                            })
                        }
                    }
                }
                that.setData({
                    submit_data: submit_data,
                    init_submit_data: { ...submit_data },
                    loading: false
                })
            }
        })
    },
    //变换下key的对应关系
    transform_meeting_data: function (conference_data) {
        var transformed_data = {};
        if (conference_data.meeting_name) {
            transformed_data.conference_name = conference_data.meeting_name
        }
        if (conference_data.short_summary) {
            transformed_data.conference_intro = conference_data.short_summary
        }
        if (conference_data.meeting_time) {
            var two_parts = conference_data.meeting_time.split(' ');
            transformed_data.date = two_parts[0];
            transformed_data.time = two_parts[1].split(':').slice(0, 2).join(':');
        }
        if (conference_data.region) {
            transformed_data.region = conference_data.region
        }
        if (conference_data.meeting_address) {
            transformed_data.conference_location = conference_data.meeting_address
        }
        if (conference_data.long_summary) {
            transformed_data.long_summary = conference_data.long_summary
        }
        if (conference_data.cover) {
            transformed_data.cover = conference_data.cover
        }
        if (conference_data.creat_identity_id) {
            transformed_data.creat_identity_id = conference_data.creat_identity_id
        }
        return transformed_data
    },
    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    save_props: function (options) {
        var query_data = { ...options };
        query_data.back = "cache"
        this.setData({
            query_data: query_data
        })
    },
    add_props: function (key, value) {
        var query_data = this.data.query_data;
        query_data[key] = value;
        this.setData({
            query_data: query_data
        });
    },
    load_identity: function () {
        this.setData({
            identities: wx.getStorageSync('publisher-identities'),
            identities_id: wx.getStorageSync("publisher-identities-ids"),
        })
    },
    onReady: function () {

    },

    /**
     * 生命周期函数--监听页面显示
     */
    onShow: function () {
        this.load_identity();
        console.log(this.data.identities, this.data.identities_id, this.data.index)
    },

    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide: function () {

    },

    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload: function () {

    },

    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh: function () {

    },

    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom: function () {

    },

    /**
     * 用户点击右上角分享
     */
    onShareAppMessage: function () {

    },
    change_step: function (go_url) {
        var query_data = this.data.query_data;
        var jump_url = go_url + gen_query_str(query_data);
        console.log("first-next:" + jump_url);
        wx.redirectTo({
            url: jump_url
        })
    },
    check_update: function () {


        var submit_data = this.data.submit_data;
        //console.log(submit_data);
        var init_submit_data = this.data.init_submit_data;
        //console.log(init_submit_data);
        for (var key in submit_data) {
            if (submit_data[key] != init_submit_data[key]) {
                return true
            }
        }
        for (var key in init_submit_data) {
            if (init_submit_data[key] != submit_data[key]) {
                return true
            }
        }
        return false
    },
    save_and_next: function () {
        var on_save=this.data.on_save
        if(on_save){
            return
        }
        this.setData({
            on_save:true
        })
        var that = this;
        if (this.valid_submit_data()) {
            var publisher = that.data.identities_id[that.data.index];
            that.add_props("publisher", publisher);
            wx.setStorageSync('first-step-cache', {
                index: that.data.index,
                submit_data: that.data.submit_data,
                publisher: publisher
            })
            if (that.check_update()) {
                var request_data = {
                    publisher: publisher,
                    step: 1,
                    data: that.data.submit_data
                };
                if (this.data.query_data.edit_id) {
                    request_data.meeting = +this.data.query_data.edit_id;
                }

                my_request({
                    url: "https://sichuangyi.demopp.in/api-conference-alpha/submit",
                    method: "POST",
                    data: request_data,
                    success: function (res) {
                        //console.log(res);
                        if (!that.data.query_data.edit_id) {
                            my_showToast_ok("新增成功", 2000)
                            that.add_props("edit_id", res.data.data.conference_id);
                            that.change_step(that.data.next_url)
                        }
                        else {
                            my_showToast_ok("保存成功", 2000)
                        }
                    },
                    fail: function (res) {
                        my_showToast_error("保存失败", 2000);
                    },
                    complete: function () {
                        //console.log("rasdsa")
                        wx.removeStorageSync("current-edit-conference")
                    that.setData({
                        on_save:false
                    })
                    }
                })
            }
            //走向下一步
            if (that.data.query_data.edit_id) {
                that.change_step(that.data.next_url);
            }
        }
    }
})